<template>
<!--  <h2>四性检测方案</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
      <el-form-item label="方案标识" prop="identification">
        <el-input v-model="queryParams.identification" placeholder="请输入方案标识" clearable style="width: 240px"/>
      </el-form-item>

      <el-form-item label="检测阶段" prop="phase">
        <el-select v-model="queryParams.phase" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="item in dict.type.DETECTION_PHASE" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="档案门类" prop="categoryId">
        <treeselect v-model="queryParams.categoryId" :options="deptOptions" clearable style="width: 240px" noResultsText="暂无数据"
                    placeholder="请选择档案门类" :disable-branch-nodes="true" :normalizer="normalizer"  />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd" v-hasPermi="['archive:fourNatures:detectionPlan:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"/>
      <el-table-column label="操作" width="350px" align="center" header-align="center">
        <template slot-scope="scope">
          <el-button  plain type="warning" @click="handleUpdate(scope.row)" v-hasPermi="['archive:fourNatures:detectionPlan:edit']">修改</el-button>
          <el-button  plain type="danger" @click="handleDelete(scope.row)" v-hasPermi="['archive:fourNatures:detectionPlan:delete']">删除</el-button>
          <el-button  plain type="info" @click="handleDetail(scope.row)" v-hasPermi="['archive:fourNatures:detectionPlan:programme']">方案明细</el-button>
        </template>
      </el-table-column>
      <el-table-column label="方案标识" prop="identification" align="center" />
      <el-table-column label="检测阶段" prop="phase" align="center" />
      <el-table-column label="档案门类" prop="categoryName" align="center" />
      <el-table-column label="状态" prop="state" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="方案更新人" prop="lastupdateName" align="center" />
      <el-table-column label="方案更新时间" prop="lastupdateTime" align="center" />
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加/修改四性检测方案 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" append-to-body>
      <el-form ref="planForm" :model="planForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="方案标识" prop="identification">
              <el-input v-model="planForm.identification" placeholder="请输入方案标识" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检测阶段" prop="phase">
              <el-select v-model="planForm.phase" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in dict.type.DETECTION_PHASE" :key="item.value" :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="档案门类" prop="categoryId">
              <treeselect v-model="planForm.categoryId" :options="deptOptions" clearable @input="changeValue" noResultsText="暂无数据"
                          placeholder="请选择档案门类" :disable-branch-nodes="true" :normalizer="normalizer" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 方案明细 -->
    <!-- 四性方案 isShow: '1', 四性记录 isShow: '2' -->
    <planDetail v-if="planOpen" :title="planTitle" :open="planOpen" ref="planRef" :isShow="'1'" @planCancelTap="planCancelTap"></planDetail>
  </div>
</template>

<script>
import estimateTableHeight from '@/mixins/estimateTableHeight'
import {
  addPlan,
  deletePlan, getConfiguration, getConfigurationDetail, getDetail,
  getPlanDetail,
  getPlanList,
  listGROUPTree,
  updatePlan
} from "@/api/archive/fourNatures/detectionPlan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import PlanDetail from "@/views/archive/fourNatures/detectionPlan/planDetail";

export default {
  name: "index",
  mixins: [estimateTableHeight], // 混入方法
  components: {PlanDetail, Treeselect },
  archive_Dicts: ['DETECTION_PHASE'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum:1,
        pageSize:10,
        identification: undefined,
        phase: undefined,
        categoryId: undefined
      },
      dataList: [],
      total: 0,
      // 树选项
      deptOptions: [],
      // 检测阶段
      phaseOption: [
        {value: '0', label: '归档'},
        {value: '1', label: '移交'},
        {value: '2', label: '长期'}
      ],

      // 新增/修改
      title: '',
      open: false,
      planForm: {},
      // 校验
      rules: {
        identification: [
          { required: true, message: "方案标识不能为空", trigger: "blur" },
          { max: 25, message: '长度不能超过25个字符', trigger: 'blur' }
        ],
        phase: [
          { required: true, message: "检测阶段不能为空" }
        ],
        categoryId: [
          { required: true, message: "档案门类不能为空", trigger: 'input'}
        ]
      },
      // 方案明细弹窗
      planOpen: false,
      planTitle: '方案明细',
      info: []
    }
  },
  created() {
    this.getDeptTree()
  },
  methods: {
    changeValue() {
      this.$refs["planForm"].validateField('categoryId');
    },
    // 获取档案门类树
    getDeptTree() {
      listGROUPTree().then(response => {
        this.deptOptions = response.data;
        this.getList()
      })
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList(){
      this.loading = true
      // console.log(this.dict.type.DETECTION_PHASE,"sdklfjksdfjksdlfjkls")
      var phaseOption=this.dict.type.DETECTION_PHASE;
      getPlanList(this.queryParams).then(response=>{
        this.dataList = response.rows
        for (let i = 0; i < response.rows.length; i++) {
          for (let j = 0; j < phaseOption.length; j++) {
            if(response.rows[i].phase == phaseOption[j].value) {
              this.dataList[i].phase = phaseOption[j].label
            }
          }
          this.dataList[i].state = response.rows[i].state.toString()
        }
        this.total = response.total
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    reset() {
      this.planForm = {
        identification: undefined,
        phase: undefined,
        categoryId: undefined
      };
    },
    // 添加
    handleAdd() {
      this.resetForm('planForm')
      this.reset();
      this.open = true;
      this.title = "添加四性方案";
    },
    // 修改
    handleUpdate(row) {
      const id = row.id
      this.resetForm('planForm')
      getPlanDetail(id).then(response=>{
        this.planForm = response.data;
        this.open = true;
        this.title = "修改四性方案";
      })
    },
    // 只能选择数据下面有children 的数据，没有children的时候禁用复选框
    normalizer(node) {

      if (node.nodeType == 'fonds') {
                if (node.children == undefined || node.children == null || !node.children.length) {

                    node['isDisabled'] = true;
                }

            }
            if (node.children == null || node.children == undefined || !node.children.length) {
                delete node.children;
            }
            return node
    },
    // 提交表单
    submitForm() {
      this.$refs["planForm"].validate(valid => {
        if (valid) {
          this.planForm.type = this.findValueById(this.deptOptions, this.planForm.categoryId)
          if (this.planForm.id != undefined) {
            // console.log(this.planForm)
            updatePlan(this.planForm).then(response=>{
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // console.log(this.planForm)
            addPlan(this.planForm).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
    findValueById(tree, categoryId) {
      // 遍历树结构数据的每个节点
      for (let i = 0; i < tree.length; i++){
        // 检查当前节点的ID是否与目标ID相等
        if (tree[i].id == categoryId) {
          // 如果相等，返回当前节点的值
          return tree[i].type;
        }
        // 检查当前节点是否有子节点
        if (tree[i].children && tree[i].children.length > 0) {
          // 递归调用函数，在子节点中查找值
          const childValue = this.findValueById(tree[i].children, categoryId);
          // 如果在子节点中找到了值，返回该值
          if (childValue != undefined && childValue != null) {
            return childValue;
          }
        }
      }
      // 如果未找到匹配的ID，返回null或其他你认为合适的默认值
      return null;
    },
    cancel() {
      this.open = false
      this.reset();
    },
    // 删除
    handleDelete(row) {
      const id = row.id
      const identification = row.identification
      this.$modal.confirm('是否确认删除方案标识为"' + identification + '"的数据项？').then(function () {
        return deletePlan(id)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 修改状态
    handleStatusChange(row) {
      updatePlan({id: row.id, state: row.state}).then(response=>{
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    // 方案明细
    handleDetail(row) {
      this.info = Object.assign({}, row);
      var phaseOption=this.dict.type.DETECTION_PHASE
      getDetail({pId: row.id}).then(response=>{
        const data = response.data
        if(data > 0) {
          for (let j = 0; j < phaseOption.length; j++) {
            if(this.info.phase ==phaseOption[j].label) {
              this.info.phase = phaseOption[j].value
            }
          }
          this.planOpen = true
          getConfigurationDetail(row.id).then(response=>{
            var treeData = response.data
            this.$nextTick(() => {
              this.$refs.planRef.init(treeData, this.info)
            })
          })
        } else {
          var phase = ''
          for (let j = 0; j < phaseOption.length; j++) {
            if(this.info.phase == phaseOption[j].label) {
              this.info.phase = phaseOption[j].value
              phase = phaseOption[j].value
            }
          }
          this.planOpen = true
          getConfiguration({code: phase}).then(response=>{
            var treeData = response.data
            this.$nextTick(() => {
              this.$refs.planRef.init(treeData, this.info)
            })
          })
        }
      })
    },
    planCancelTap() {
      this.planOpen = false
    }
  }
}
</script>

<style scoped>

</style>
